// 第一章：服务之旅 - 解谜系统
// 包含两个主要解谜：情感陪伴解谜和气候应对解谜

// 解谜1：情感陪伴系统优化
class EmotionalCompanionPuzzle {
    constructor() {
        this.currentStep = 0;
        this.totalSteps = 4;
        this.completed = false;
        this.timeLeft = 180; // 3分钟倒计时
        this.timer = null;
        
        this.steps = [
            {
                title: "情感识别",
                description: "准确识别王奶奶的情感状态和需求",
                completed: false
            },
            {
                title: "连接方案",
                description: "设计适合老年人的数字连接方案",
                completed: false
            },
            {
                title: "实施指导",
                description: "耐心指导王奶奶使用新工具",
                completed: false
            },
            {
                title: "持续支持",
                description: "建立长期的情感支持机制",
                completed: false
            }
        ];
    }

    render(container) {
        this.container = container;
        const puzzleHTML = `
            <div class="story-content">
                <h2>情感陪伴系统优化</h2>
                
                <div class="scenario-description">
                    <h3>场景描述</h3>
                    <p>王奶奶因思念远在国外的儿子而情绪低落，需要你帮助她建立新的情感连接方式。</p>
                    <div class="key-challenges">
                        <strong>关键挑战：</strong>
                        <ul>
                            <li>克服老年人对科技的恐惧</li>
                            <li>找到适合她生活节奏的连接方式</li>
                            <li>不仅解决当前问题，还要建立长期机制</li>
                        </ul>
                    </div>
                </div>

                <div class="puzzle-steps">
                    <h3>解谜步骤</h3>
                    ${this.steps.map((step, index) => `
                        <div class="step ${step.completed ? 'completed' : ''} ${index === this.currentStep ? 'active' : ''}" data-step="${index}">
                            <div class="step-number">${index + 1}</div>
                            <div class="step-content">
                                <h4>${step.title}</h4>
                                <p>${step.description}</p>
                            </div>
                        </div>
                    `).join('')}
                </div>

                <div class="current-step-content" id="current-step-content">
                    ${this.getCurrentStepContent()}
                </div>

                <div class="puzzle-actions">
                    <button id="puzzle-help" class="choice-btn">提示</button>
                    <button id="puzzle-submit" class="choice-btn" disabled>提交方案</button>
                </div>
            </div>
        `;

        container.innerHTML = puzzleHTML;
        this.attachEventListeners();
        
        // 确保提交按钮初始状态为禁用
        const submitBtn = document.getElementById('puzzle-submit');
        if (submitBtn) {
            submitBtn.disabled = true;
        }
    }

    getCurrentStepContent() {
        switch(this.currentStep) {
            case 0:
                return `
                    <h3>步骤1：情感识别</h3>
                    <div class="step-content">
                        <p>请分析王奶奶的情感状态，选择最准确的描述：</p>
                        <div class="options">
                            <label class="option">
                                <input type="radio" name="emotion" value="lonely">
                                <span>主要是孤独感，需要陪伴</span>
                            </label>
                            <label class="option">
                                <input type="radio" name="emotion" value="nostalgic">
                                <span>主要是怀旧情绪，需要回忆美好</span>
                            </label>
                            <label class="option">
                                <input type="radio" name="emotion" value="anxious">
                                <span>主要是焦虑，担心与儿子失去联系</span>
                            </label>
                            <label class="option">
                                <input type="radio" name="emotion" value="complex">
                                <span>复杂的情感混合：思念+担忧+适应困难</span>
                            </label>
                        </div>
                    </div>
                `;
            case 1:
                return `
                    <h3>步骤2：连接方案设计</h3>
                    <div class="step-content">
                        <p>基于情感识别结果，设计最适合王奶奶的数字连接方案：</p>
                        <div class="options">
                            <label class="option">
                                <input type="checkbox" name="solution" value="video">
                                <span>简单视频通话（一键操作）</span>
                            </label>
                            <label class="option">
                                <input type="checkbox" name="solution" value="schedule">
                                <span>定期通话提醒和安排</span>
                            </label>
                            <label class="option">
                                <input type="checkbox" name="solution" value="community">
                                <span>加入社区老年活动群</span>
                            </label>
                            <label class="option">
                                <input type="checkbox" name="solution" value="memory">
                                <span>创建数字回忆相册共享</span>
                            </label>
                        </div>
                    </div>
                `;
            case 2:
                return `
                    <h3>步骤3：实施指导策略</h3>
                    <div class="step-content">
                        <p>如何以最合适的方式教王奶奶使用新工具？</p>
                        <div class="options">
                            <label class="option">
                                <input type="radio" name="teaching" value="patience">
                                <span>极有耐心，多次重复教学</span>
                            </label>
                            <label class="option">
                                <input type="radio" name="teaching" value="simple">
                                <span>从最简单的功能开始</span>
                            </label>
                            <label class="option">
                                <input type="radio" name="teaching" value="family">
                                <span>让家人一起参与教学</span>
                            </label>
                            <label class="option">
                                <input type="radio" name="teaching" value="practice">
                                <span>边学边练习，及时巩固</span>
                            </label>
                        </div>
                    </div>
                `;
            case 3:
                return `
                    <h3>步骤4：长期支持机制</h3>
                    <div class="step-content">
                        <p>如何确保王奶奶能够持续受益，不会再次陷入孤独？</p>
                        <div class="options">
                            <label class="option">
                                <input type="checkbox" name="support" value="monitor">
                                <span>定期情感状态监测</span>
                            </label>
                            <label class="option">
                                <input type="checkbox" name="support" value="expand">
                                <span>逐步扩展她的社交圈</span>
                            </label>
                            <label class="option">
                                <input type="checkbox" name="support" value="skills">
                                <span>持续学习新的数字技能</span>
                            </label>
                            <label class="option">
                                <input type="checkbox" name="support" value="feedback">
                                <span>定期收集反馈并调整方案</span>
                            </label>
                        </div>
                    </div>
                `;
            default:
                return '';
        }
    }

    start() {
        // 解谜已改为正常剧情模式，直接开始
    }

    attachEventListeners() {
        // 移除旧的事件监听器（如果存在）
        if (this.helpHandler) {
            document.getElementById('puzzle-help').removeEventListener('click', this.helpHandler);
        }
        if (this.submitHandler) {
            document.getElementById('puzzle-submit').removeEventListener('click', this.submitHandler);
        }
        
        // 为选项移除旧的事件监听器（如果存在）
        if (this.optionHandlers) {
            const options = document.querySelectorAll('.option input');
            options.forEach((option, index) => {
                if (this.optionHandlers[index]) {
                    option.removeEventListener('change', this.optionHandlers[index]);
                }
            });
        }

        // 定义新的事件处理函数并绑定
        this.helpHandler = () => {
            this.showHint();
        };
        this.submitHandler = () => {
            this.submitAnswer();
        };
        
        document.getElementById('puzzle-help').addEventListener('click', this.helpHandler);
        document.getElementById('puzzle-submit').addEventListener('click', this.submitHandler);

        // 为选项添加事件监听
        this.optionHandlers = [];
        const options = document.querySelectorAll('.option input');
        options.forEach(option => {
            const handler = () => {
                // 检查当前步骤的选项选择状态
                const currentInputs = document.querySelectorAll('.option input');
                let hasSelection = false;
                
                if (this.currentStep === 1 || this.currentStep === 3) {
                    // 复选框步骤 - 检查是否至少选择了一个
                    currentInputs.forEach(input => {
                        if (input.checked) hasSelection = true;
                    });
                } else {
                    // 单选按钮步骤 - 检查是否选择了
                    currentInputs.forEach(input => {
                        if (input.checked) hasSelection = true;
                    });
                }
                
                document.getElementById('puzzle-submit').disabled = !hasSelection;
            };
            this.optionHandlers.push(handler);
            option.addEventListener('change', handler);
        });
        
        // 初始状态设置
        setTimeout(() => {
            document.getElementById('puzzle-submit').disabled = true;
        }, 100);
    }

    showHint() {
        const hints = [
            "王奶奶的情感是复杂且多层次的，不要简化她的感受。",
            "考虑老年人的接受能力，选择最简单但最有效的方案。",
            "耐心和重复是成功的关键。",
            "建立可持续的机制比一次性解决方案更重要。"
        ];
        
        const messageDiv = document.createElement('div');
        messageDiv.className = 'hint-message';
        messageDiv.innerHTML = `
            <div class="story-text">
                <p><strong>思考提示：</strong></p>
                <p>${hints[this.currentStep] || "仔细思考每一步的影响"}</p>
            </div>
        `;
        
        const content = document.getElementById('current-step-content');
        content.appendChild(messageDiv);
        
        // 3秒后自动消失
        setTimeout(() => {
            if (messageDiv.parentNode) {
                messageDiv.parentNode.removeChild(messageDiv);
            }
        }, 3000);
    }

    submitAnswer() {
        this.steps[this.currentStep].completed = true;
        
        if (this.currentStep < this.totalSteps - 1) {
            this.currentStep++;
            this.render(this.container);
        } else {
            this.completePuzzle();
        }
    }



    completePuzzle() {
        this.completed = true;
        
        // 移除所有事件监听器
        if (this.helpHandler) {
            document.getElementById('puzzle-help').removeEventListener('click', this.helpHandler);
        }
        if (this.submitHandler) {
            document.getElementById('puzzle-submit').removeEventListener('click', this.submitHandler);
        }
        
        if (this.optionHandlers) {
            const options = document.querySelectorAll('.option input');
            options.forEach((option, index) => {
                if (this.optionHandlers[index]) {
                    option.removeEventListener('change', this.optionHandlers[index]);
                }
            });
        }
        
        gameState.completePuzzle('elderly_companion');
    }

    // 添加complete方法以匹配PuzzleManager的调用
    complete() {
        this.completePuzzle();
    }
}

// 解谜2：城市气候适应系统
class ClimateAdaptationPuzzle {
    constructor() {
        this.currentStep = 0;
        this.totalSteps = 5;
        this.completed = false;
        this.resources = {
            budget: 100, // 预算点数
            manpower: 50, // 人力点数
            technology: 75, // 技术点数
            time: 14 // 天数
        };
        this.decisions = [];
    }

    render(container) {
        const puzzleHTML = `
            <div class="puzzle-container">
                <div class="puzzle-header">
                    <h2>城市气候适应系统</h2>
                    <div class="resource-bar">
                        <div class="resource">
                            <label>预算: <span id="budget">${this.resources.budget}</span></label>
                            <div class="resource-fill" style="width: ${this.resources.budget}%"></div>
                        </div>
                        <div class="resource">
                            <label>人力: <span id="manpower">${this.resources.manpower}</span></label>
                            <div class="resource-fill" style="width: ${this.resources.manpower}%"></div>
                        </div>
                        <div class="resource">
                            <label>技术: <span id="technology">${this.resources.technology}</span></label>
                            <div class="resource-fill" style="width: ${this.resources.technology}%"></div>
                        </div>
                        <div class="resource">
                            <label>时间: <span id="time">${this.resources.time}</span>天</label>
                        </div>
                    </div>
                </div>

                <div class="puzzle-content">
                    <div class="scenario-description">
                        <h3>气候危机场景</h3>
                        <p>城市面临极端气候异常，需要在有限资源下制定最优的应对策略。</p>
                        <div class="climate-impact">
                            <strong>当前影响：</strong>
                            <ul>
                                <li>气温异常波动：±15°C</li>
                                <li>农作物损失：30%</li>
                                <li>健康风险增加：300%</li>
                                <li>经济损失：每日2亿元</li>
                            </ul>
                        </div>
                    </div>

                    <div class="strategy-options">
                        <h3>应对策略选择</h3>
                        <div id="strategy-content">
                            ${this.getCurrentStrategyContent()}
                        </div>
                    </div>

                    <div class="puzzle-actions">
                        <button id="strategy-help" class="help-btn">数据支持</button>
                        <button id="strategy-submit" class="submit-btn">实施策略</button>
                        <button id="strategy-reset" class="reset-btn">重新规划</button>
                    </div>
                </div>

                <div class="impact-preview">
                    <h3>预期影响</h3>
                    <div id="impact-display">
                        ${this.calculateImpact()}
                    </div>
                </div>
            </div>
        `;

        container.innerHTML = puzzleHTML;
        this.attachStrategyListeners();
    }

    getCurrentStrategyContent() {
        switch(this.currentStep) {
            case 0:
                return `
                    <h4>短期应急措施 (1-3天)</h4>
                    <div class="strategy-grid">
                        <div class="strategy-card" data-strategy="emergency-shelter">
                            <h5>紧急避难所</h5>
                            <p>开放所有公共建筑作为临时避难所</p>
                            <div class="cost">预算: 20, 人力: 15, 技术: 10</div>
                            <div class="impact">减少健康风险50%</div>
                        </div>
                        <div class="strategy-card" data-strategy="medical-support">
                            <h5>医疗支援</h5>
                            <p>增派医疗队伍，储备应急药品</p>
                            <div class="cost">预算: 25, 人力: 20, 技术: 15</div>
                            <div class="impact">降低死亡率80%</div>
                        </div>
                        <div class="strategy-card" data-strategy="food-reserve">
                            <h5>食物储备</h5>
                            <p>紧急调运和分发食物</p>
                            <div class="cost">预算: 30, 人力: 10, 技术: 5</div>
                            <div class="impact">保障基本生活需求</div>
                        </div>
                    </div>
                `;
            case 1:
                return `
                    <h4>中期适应措施 (4-7天)</h4>
                    <div class="strategy-grid">
                        <div class="strategy-card" data-strategy="temperature-control">
                            <h5>温控系统</h5>
                            <p>优化城市供暖/制冷系统</p>
                            <div class="cost">预算: 35, 人力: 15, 技术: 25</div>
                            <div class="impact">改善室内环境舒适度</div>
                        </div>
                        <div class="strategy-card" data-strategy="transport-adapt">
                            <h5>交通适应</h5>
                            <p>调整公共交通应对极端天气</p>
                            <div class="cost">预算: 20, 人力: 20, 技术: 30</div>
                            <div class="impact">维持城市运行效率</div>
                        </div>
                        <div class="strategy-card" data-strategy="crop-protection">
                            <h5>农作物保护</h5>
                            <p>采用技术手段保护农作物</p>
                            <div class="cost">预算: 25, 人力: 10, 技术: 35</div>
                            <div class="impact">减少农业损失60%</div>
                        </div>
                    </div>
                `;
            case 2:
                return `
                    <h4>长期预警系统 (8-14天)</h4>
                    <div class="strategy-grid">
                        <div class="strategy-card" data-strategy="ai-monitoring">
                            <h5>AI监测网络</h5>
                            <p>建立智能气候监测预警系统</p>
                            <div class="cost">预算: 40, 人力: 15, 技术: 50</div>
                            <div class="impact">提前72小时预警</div>
                        </div>
                        <div class="strategy-card" data-strategy="community-network">
                            <h5>社区互助网</h5>
                            <p>建立社区级应急响应网络</p>
                            <div class="cost">预算: 15, 人力: 30, 技术: 20</div>
                            <div class="impact">增强社区韧性</div>
                        </div>
                        <div class="strategy-card" data-strategy="policy-framework">
                            <h5>政策框架</h5>
                            <p>制定极端天气应对标准</p>
                            <div class="cost">预算: 20, 人力: 25, 技术: 15</div>
                            <div class="impact">建立长期制度保障</div>
                        </div>
                    </div>
                `;
            case 3:
                return `
                    <h4>资源分配优化</h4>
                    <div class="resource-allocation">
                        <h5>剩余资源分配</h5>
                        <div class="allocation-controls">
                            <div class="allocation-item">
                                <label>弱势群体保护:</label>
                                <input type="range" id="vulnerable-protection" min="0" max="100" value="50">
                                <span id="vulnerable-value">50%</span>
                            </div>
                            <div class="allocation-item">
                                <label>基础设施维护:</label>
                                <input type="range" id="infrastructure" min="0" max="100" value="30">
                                <span id="infrastructure-value">30%</span>
                            </div>
                            <div class="allocation-item">
                                <label>经济恢复:</label>
                                <input type="range" id="economic-recovery" min="0" max="100" value="20">
                                <span id="economic-value">20%</span>
                            </div>
                        </div>
                    </div>
                `;
            case 4:
                return `
                    <h4>最终方案确认</h4>
                    <div class="final-review">
                        <h5>综合应对策略</h5>
                        <div id="final-strategy">
                            ${this.generateFinalStrategy()}
                        </div>
                        <div class="success-metrics">
                            <h6>预期成效</h6>
                            <ul>
                                <li>健康风险降低：85%</li>
                                <li>经济损失减少：60%</li>
                                <li>社会稳定性：提升90%</li>
                                <li>未来应对能力：增强200%</li>
                            </ul>
                        </div>
                    </div>
                `;
            default:
                return '';
        }
    }

    attachStrategyListeners() {
        document.getElementById('strategy-help').addEventListener('click', () => {
            this.showDataSupport();
        });

        document.getElementById('strategy-submit').addEventListener('click', () => {
            this.submitStrategy();
        });

        document.getElementById('strategy-reset').addEventListener('click', () => {
            this.resetStrategy();
        });

        // 策略卡片选择
        const strategyCards = document.querySelectorAll('.strategy-card');
        strategyCards.forEach(card => {
            card.addEventListener('click', () => {
                this.selectStrategy(card.dataset.strategy);
            });
        });

        // 资源分配滑块
        const sliders = document.querySelectorAll('input[type="range"]');
        sliders.forEach(slider => {
            slider.addEventListener('input', (e) => {
                this.updateAllocation(e.target);
            });
        });
    }

    showDataSupport() {
        const data = [
            "根据历史数据，极端天气期间老年人死亡率增加300%",
            "社区互助网络可以减少政府应急响应成本40%",
            "AI预警系统可以提前72小时预测极端天气，减少损失50%",
            "综合应对策略的效果是单一策略的3-5倍"
        ];
        alert(data[this.currentStep] || "基于大数据分析制定最优策略");
    }

    selectStrategy(strategy) {
        this.decisions.push(strategy);
        this.updateResourceDisplay();
        
        if (this.currentStep < this.totalSteps - 1) {
            this.currentStep++;
            this.render();
        }
    }

    updateAllocation(slider) {
        const valueSpan = document.getElementById(slider.id + '-value');
        valueSpan.textContent = slider.value + '%';
        this.calculateImpact();
    }

    updateResourceDisplay() {
        document.getElementById('budget').textContent = this.resources.budget;
        document.getElementById('manpower').textContent = this.resources.manpower;
        document.getElementById('technology').textContent = this.resources.technology;
        document.getElementById('time').textContent = this.resources.time;
    }

    calculateImpact() {
        return `
            <div class="impact-grid">
                <div class="impact-item">
                    <h6>健康保护</h6>
                    <div class="impact-bar">
                        <div class="fill" style="width: 85%"></div>
                    </div>
                </div>
                <div class="impact-item">
                    <h6>经济恢复</h6>
                    <div class="impact-bar">
                        <div class="fill" style="width: 70%"></div>
                    </div>
                </div>
                <div class="impact-item">
                    <h6>社会稳定</h6>
                    <div class="impact-bar">
                        <div class="fill" style="width: 90%"></div>
                    </div>
                </div>
            </div>
        `;
    }

    generateFinalStrategy() {
        return `
            <div class="strategy-summary">
                <h6>多层次应对框架</h6>
                <ol>
                    <li><strong>短期应急：</strong>紧急避难所 + 医疗支援</li>
                    <li><strong>中期适应：</strong>温控系统 + 交通调整</li>
                    <li><strong>长期建设：</strong>AI预警 + 社区网络</li>
                    <li><strong>资源优化：</strong>弱势群体优先保护</li>
                </ol>
            </div>
        `;
    }

    submitStrategy() {
        this.completed = true;
        gameState.completePuzzle('climate_analysis');
        storyManager.displayScene(storyManager.getSceneIndexById('puzzle_2_complete'));
    }

    start() {
        // 气候解谜不需要计时器，直接开始
    }

    resetStrategy() {
        this.currentStep = 0;
        this.resources = {
            budget: 100,
            manpower: 50,
            technology: 75,
            time: 14
        };
        this.decisions = [];
        this.render();
    }
}

// 注册第一章的解谜
if (typeof puzzleManager !== 'undefined') {
    puzzleManager.registerPuzzle('elderly_companion', EmotionalCompanionPuzzle);
    puzzleManager.registerPuzzle('climate_analysis', ClimateAdaptationPuzzle);
}

// 第一章专用工具函数
class Chapter1Utils {
    static calculateEmotionalImpact(solution) {
        const impacts = {
            loneliness: -30,
            connection: +50,
            independence: +20,
            happiness: +40
        };
        return impacts;
    }

    static evaluateClimateStrategy(strategy) {
        const score = {
            health: 0,
            economy: 0,
            stability: 0,
            sustainability: 0
        };
        
        // 基于策略组合计算得分
        if (strategy.includes('emergency-shelter')) score.health += 25;
        if (strategy.includes('medical-support')) score.health += 30;
        if (strategy.includes('community-network')) score.stability += 40;
        if (strategy.includes('ai-monitoring')) score.sustainability += 35;
        
        return score;
    }
}

// 全局访问
window.chapter1Utils = Chapter1Utils;